package com.frinder.seata.storage.service;

import com.frinder.seata.data.domain.model.Storage;
import com.frinder.seata.data.domain.service.IStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @ClassName BizStorageService
 * @Description 库存服务
 * @Author frinder
 * @Date 2020/8/18 15:31
 * @Verion 1.0
 */
@Slf4j
@Service
public class BizStorageService {

    @Resource
    private IStorageService storageService;

    /**
     * 扣减库存
     *
     * @param productId
     * @param qty
     */
    public void decrease(long productId, int qty) {
        log.info(">> 开始扣减商品[{}]库存，扣减数量[{}]", productId, qty);
        Optional.ofNullable(storageService.findById(productId))
                .ifPresent(o -> {
                    Storage storage = Storage.builder()
                            .id(o.getId())
                            .residue(o.getResidue() - qty)
                            .used(o.getUsed() + qty)
                            .build();
                    storageService.update(storage);
                    log.info("<< 扣减商品[{}]库存，扣减数量[{}]", productId, qty);
                });
    }

}
